
#import "WXSHypnosisViewController.h"
#import "WXSHypnosisHeaderView.h"
#import <AVFoundation/AVFoundation.h>

static NSString * const identifier = @"cell";

@interface WXSHypnosisViewController ()<UITableViewDelegate, UITableViewDataSource, WXSHypnosisHeaderViewDelegate>

@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) WXSHypnosisHeaderView * headerView;//头部view
@property (nonatomic, strong) AVPlayer * player;
@property (nonatomic, copy) NSArray * musicArray;//音乐数组
@property (nonatomic, copy) NSArray * musicNameArray;//音乐名数组
@property (nonatomic, copy) NSString * musicURL;//音乐地址
@property (nonatomic, assign) NSInteger currentIndex;//当前播放的下标
@property (nonatomic, strong) id observer;//时间观察者
@property (nonatomic, assign) BOOL isFirst;//是否是首次播放
@property (nonatomic, strong) NSIndexPath *indexPath;//记录当前选中的cell
@property (nonatomic, strong) NSIndexPath * pastIndexPath;//记录上次选中的cell
@property (nonatomic, assign) BOOL isSingle;//单曲
@property (nonatomic, assign) BOOL isSelected;//是否选中
@property (nonatomic, assign) BOOL isPlay;//是否播放
@property (nonatomic, strong) NSTimer * timer;//定时器

- (void)_initializeAppearance;//初始化

@end

@implementation WXSHypnosisViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentIndex = 0;
    self.isFirst = YES;
    self.isPlay = YES;
    self.isSelected = NO;
    [self _initializeAppearance];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"听一曲";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playPatternChanged:) name:@"noti" object:nil];
}

#pragma mark - private method

- (void)_initializeAppearance
{
//    [self setupLeftBarButtonWithTitle:@"设置" action:@selector(leftBarButtonTapped:)];
//    [self setupRightBarButtonWithTitle:@"我的" action:@selector(rightBarButtonTapped:)];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.headerView];
    self.headerView.musicName.text = self.musicNameArray[self.currentIndex];
    self.musicURL = [[NSBundle mainBundle] pathForAuxiliaryExecutable:self.musicArray[0]];
}

- (void)playerPlayWithArrayIndex:(NSInteger)index
{
    self.musicURL = [[NSBundle mainBundle] pathForAuxiliaryExecutable:self.musicArray[index]];
    if (!self.isFirst)
    {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
        [self.player removeTimeObserver:_observer];
    }
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:[NSURL fileURLWithPath:self.musicURL]];
    [self.player replaceCurrentItemWithPlayerItem:item];
    [self.player play];
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    self.isFirst = NO;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"])
    {
        if (playerItem.status == AVPlayerStatusReadyToPlay)
        {
            [self.player play];
            [self getCurrentTime:playerItem];
        }
    }
}

- (void)getCurrentTime:(AVPlayerItem *)item
{
    __weak typeof(self) myself = self;
    _observer = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float currentTime = CMTimeGetSeconds(item.currentTime);
        float totalTime = CMTimeGetSeconds(item.duration);
        if (currentTime == totalTime)
        {
            [myself next];
        }
    }];
}

- (void)previous//上一曲
{
    self.pastIndexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
    if (_isSingle)
    {
        self.currentIndex -= 0;
        [self playerPlayWithArrayIndex:self.currentIndex];
    }
    else
    {
        self.currentIndex --;
        [self playerPlayWithArrayIndex:self.currentIndex < 0 ? self.currentIndex = self.musicNameArray.count - 1 : self.currentIndex];
        self.indexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
        [self cellSetAccessoryTypeWithPassIndexPath:self.pastIndexPath currentIndexPath:self.indexPath];
    }
    self.headerView.musicName.text = self.musicNameArray[self.currentIndex];
    [self.headerView.playButton setImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
}

- (void)next//下一曲
{
    self.pastIndexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
    if (_isSingle)
    {
        self.currentIndex += 0;
        [self playerPlayWithArrayIndex:self.currentIndex];
    }
    else
    {
        self.currentIndex ++;
        [self playerPlayWithArrayIndex:self.currentIndex > self.musicNameArray.count - 1 ? self.currentIndex = 0 : self.currentIndex];
        self.indexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
        [self cellSetAccessoryTypeWithPassIndexPath:self.pastIndexPath currentIndexPath:self.indexPath];
    }
    self.headerView.musicName.text = self.musicNameArray[self.currentIndex];
    [self.headerView.playButton setImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
}

- (void)cellSetAccessoryTypeWithPassIndexPath:(NSIndexPath *)passIndexPath currentIndexPath:(NSIndexPath *)currentIndexPath
{
    UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:currentIndexPath];
    [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    [cell setSelected:true];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [self tableView:self.tableView didDeselectRowAtIndexPath:passIndexPath];
}

- (void)playPatternChanged:(NSNotification *)notification
{
    NSDictionary *pattern = notification.userInfo;
    
    if ([pattern[@"pattern"] isEqualToString:@"single"])
    {
        _isSingle = YES;
    }
    else
    {
        _isSingle = NO;
    }
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self tableView:tableView didDeselectRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
    self.currentIndex = indexPath.row;//记录被选择的row
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    self.headerView.musicName.text = self.musicNameArray[indexPath.row];
    [self playerPlayWithArrayIndex:indexPath.row];
    [self.headerView.playButton setImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
    self.isPlay = NO;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
    view.backgroundColor = [UIColor lightGrayColor];
    view.alpha = 0.8;
//    UILabel *label = [[UILabel alloc]init];
//    label.frame = CGRectMake(0, 0, 100, 21);
//    label.center = view.center;
//    label.font = [UIFont systemFontOfSize:12];
//    label.textAlignment = NSTextAlignmentCenter;
//    label.textColor = TEXT_COLOR;
//    [view addSubview:label];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.5;
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.musicNameArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.textLabel.text = self.musicNameArray[indexPath.row];
    cell.textLabel.textColor = TEXT_COLOR;
    cell.textLabel.font = [UIFont systemFontOfSize:12];
    cell.backgroundColor = [UIColor clearColor];
    cell.tintColor = [UIColor colorWithRed:0.049 green:1.000 blue:0.934 alpha:1.000];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    self.indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    if (indexPath.row == 0)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }

    return cell;
}

#pragma mark - WXSHypnosisHeaderViewDelegate

- (void)buttonTaped:(UIButton *)sender
{
    switch (sender.tag)
    {
        case 101://上一曲
        {
            [self previous];
        }
            break;
        case 102://下一曲
        {
            [self next];
        }
            break;
        case 103://播放or暂停
        {
            if (self.isPlay)
            {
                [self.headerView.playButton setImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
                [self.player play];
            }
            else
            {
                [self.headerView.playButton setImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
                [self.player pause];
            }
            self.isPlay = !self.isPlay;
        }
            break;
        case 104://播放模式
        {
            self.isSelected = !self.isSelected;
            NSDictionary *patternDic;
            if (self.isSelected)
            {
                [self.headerView.typeButton setImage:[UIImage imageNamed:@"单曲循环"] forState:UIControlStateNormal];
                patternDic = @{@"pattern":@"single"};
            }
            else
            {
                [self.headerView.typeButton setImage:[UIImage imageNamed:@"循环"] forState:UIControlStateNormal];
                patternDic = @{@"pattern":@"circle"};
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"noti" object:nil userInfo:patternDic];
        }
            break;
        case 105://定时
        {
            __block int time;
            [SYAlert showSheetAlertWithTitle:@"请设置定时时长" message:nil buttonNames:@[@"15min", @"30min", @"60min", @"90min"] buttonAction:^(int index) {
                switch (index)
                {
                    case 0:
                        time = 1;
                        [self.headerView.timeButton setImage:[UIImage imageNamed:@"15"] forState:UIControlStateNormal];
                        break;
                    case 1:
                        time = 2;
                        [self.headerView.timeButton setImage:[UIImage imageNamed:@"30"] forState:UIControlStateNormal];
                        break;
                    case 2:
                        time = 3;
                        [self.headerView.timeButton setTitle:@"45" forState:UIControlStateNormal];
                        break;
                    case 3:
                        time = 4;
                        [self.headerView.timeButton setTitle:@"60" forState:UIControlStateNormal];
                        break;
                        
                    default:
                        break;
                }
                _timer = [NSTimer scheduledTimerWithTimeInterval:time * 60 target:self selector:@selector(playPause) userInfo:nil repeats:NO];
                [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
            }];
        }
            break;
        case 106://下载
            WXSLog(@"下载");
            break;
            
        default:
            break;
    }
}

#pragma mark - action

- (void)playPause
{
    [self.player pause];
    [self.headerView.playButton setTitle:@"播放" forState:UIControlStateNormal];
    [_timer invalidate];
}

//- (void)leftBarButtonTapped:(UIButton *)sender
//{
//    WXSLog(@"3");
//}
//
//- (void)rightBarButtonTapped:(UIButton *)sender
//{
//    WXSLog(@"4");
//}

#pragma mark - lazy load

- (UITableView *)tableView
{
    if (_tableView == nil)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64 + 250 * kScreenHeightScale, kScreenWidth, kScreenHeight - 49 - 250 * kScreenHeightScale - 64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:identifier];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _tableView;
}

- (WXSHypnosisHeaderView *)headerView
{
    if (_headerView == nil)
    {
        _headerView = [WXSHypnosisHeaderView loadHeaderView];
        _headerView.frame = CGRectMake(0, 64, kScreenWidth, 250 * kScreenHeightScale);
        _headerView.delegate = self;
    }
    return _headerView;
}

- (AVPlayer *)player
{
    if (_player == nil)
    {
        _player = [[AVPlayer alloc]initWithURL:[NSURL fileURLWithPath:self.musicURL]];
    }
    return _player;
}

- (NSArray *)musicArray
{
    if (_musicArray == nil)
    {
        _musicArray = @[@"不才-岁月神偷.mp3", @"张靓颖-如果这就是爱情.mp3", @"张靓颖-饿狼传说 (Live).mp3", @"张韶涵-第一页.mp3", @"张韶涵-终于.mp3"];
    }
    return _musicArray;
}

- (NSArray *)musicNameArray
{
    if (_musicNameArray == nil)
    {
        _musicNameArray = @[@"不才-岁月神偷", @"张靓颖-如果这就是爱情", @"张靓颖-饿狼传说 (Live)", @"张韶涵-第一页", @"张韶涵-终于"];
    }
    return _musicNameArray;
}

@end
